/*
 * @Author: doing
 * @Date: 2023-08-10 11:21:59
 * @LastEditors: git config user.name && git config user.email
 * @LastEditTime: 2023-08-23 18:21:57
 * @FilePath: \admin\src\composables\useManager.js
 * @Description: 
 * 对header的组件的一些方法封装
 * Copyright (c) 2023 by 1540265624@qq.com, All Rights Reserved. 
 */

import { ref, reactive } from 'vue'
import { logout, updatepassword } from "~/api/manager"
import { showModal, toast } from "~/composables/util"
import { useRouter } from "vue-router"
import { useStore } from "vuex"

const loginUrl = import.meta.env.VITE_AUTH_CENTER_URL

export function useRepassword() {
    const router = useRouter()
    const store = useStore()
    // 修改密码
    const formDrawerRef = ref(null)
    const form = reactive({
        oldpassword: "",
        password: "",
        repassword: ""
    })

    const rules = {
        oldpassword: [
            {
                required: true,
                message: '旧密码不能为空',
                trigger: 'blur'
            },
        ],
        password: [
            {
                required: true,
                message: '新密码不能为空',
                trigger: 'blur'
            },
        ],
        repassword: [
            {
                required: true,
                message: '确认密码不能为空',
                trigger: 'blur'
            },
        ]
    }

    const formRef = ref(null)
    const onSubmit = () => {
        formRef.value.validate((valid) => {
            console.log('提交的数据:')
            console.log(form)
            if (!valid) {
                return false
            }
            formDrawerRef.value.showLoading()
            updatepassword(form)
                .then(res => {
                    toast("修改密码成功，请重新登录")
                    store.dispatch("logout")  //删除掉token
                    window.location.href =`${loginUrl}?redirectURL=${window.location.href}`
                })
                .finally(() => {
                    formDrawerRef.value.hideLoading()
                })
        })
    }

    const openRePasswordForm = () => formDrawerRef.value.open()

    return {
        formDrawerRef,
        form,
        rules,
        formRef,
        onSubmit,
        openRePasswordForm
    }
}

export function useLogout() {
    const store = useStore()
    function handleLogout() {
        showModal("是否要退出登录？").then(async (res) => {
            await toast('正在删除中...','info', false, 3000)
            toast("退出登录成功")
            store.dispatch("logout") //删除掉token
            window.location.href =`${loginUrl}?redirectURL=${window.location.href}`
        })
    }

    return {
        handleLogout
    }
}
